package main

import (
	"flag"
	"fmt"
	"io"
	"net"
	"os"
)

type Client struct {
	ServerIp   string
	ServerPort int
	Name       string
	conn       net.Conn
	flag       int
}

func NewClient(serverIp string, port int) *Client {
	//创建客户端对象
	client := &Client{
		ServerIp:   serverIp,
		ServerPort: port,
		flag:       999,
	}
	//连接服务器
	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIp, port))
	if err != nil {
		fmt.Println("net.Dial err:", err)
		return nil
	}
	client.conn = conn
	return client
}

//查询在线用户
func (client *Client) SearchAll() {
	sendMsg := "who\n"
	_, err := client.conn.Write([]byte(sendMsg))
	if err != nil {
		fmt.Println("conn write err:", err)
		return
	}

}

//私聊模式
func (client *Client) PrivateChat() {

	client.SearchAll()

	var chaMsg string
	var who string

	fmt.Println(">>>>>你想谁聊天，exit推出.")
	fmt.Scanln(&who)

	fmt.Println(">>>>>请输入聊天内容，exit推出.")
	fmt.Scanln(&chaMsg)

	for chaMsg != "exit" || who != "exit" {
		if len(chaMsg) != 0 {

			sendMsg := "to|" + who + "|" + chaMsg + "\n"
			_, err := client.conn.Write([]byte(sendMsg))
			if err != nil {
				fmt.Println("conn write err:", err)
				break

			}
		}

		chaMsg = ""
		who = ""

		client.SearchAll()
		fmt.Println(">>>>>你想谁聊天，exit推出.")
		fmt.Scanln(&who)

		fmt.Println(">>>>>请输入聊天内容，exit推出.")
		fmt.Scanln(&chaMsg)

	}
}

//公聊模式
func (client *Client) PublicChat() {
	var chaMsg string

	fmt.Println(">>>>>请输入聊天内容，exit推出.")
	fmt.Scanln(&chaMsg)

	for chaMsg != "exit" {
		if len(chaMsg) != 0 {

			sendMsg := chaMsg + "\n"
			_, err := client.conn.Write([]byte(sendMsg))
			if err != nil {
				fmt.Println("conn write err:", err)
				break

			}
		}
		chaMsg = ""
		fmt.Println(">>>>>请输入聊天内容，exit推出.")
		fmt.Scanln(&chaMsg)

	}

}

//更新用户名
func (clinet *Client) UpdateName() bool {
	fmt.Println(">>>>>请输入更名的名字：<<<<")
	fmt.Scanln(&clinet.Name)
	sendMsg := "rename|" + clinet.Name + "\n"
	_, err := clinet.conn.Write([]byte(sendMsg))

	if err != nil {
		fmt.Println("conn.Write  err:", err)
		return false
	}

	return true
}

func (client *Client) DealRespone() {
	//一旦有client.conn 有数据  就直接copy到studout标准输出上   永久阻塞监听
	io.Copy(os.Stdout, client.conn)
	//上文等同于
	/*
	    for{
			buff:=make([]byte,4096)
	    	client.conn.Read(buff)
	    	fmt.Println(buff)
		}*/

}

func (clinet *Client) menu() bool {
	var flag int

	fmt.Println("1.公聊模式")
	fmt.Println("2.私聊模式")
	fmt.Println("3.更新用户名")
	fmt.Println("0.推出 ")
	fmt.Scanln(&flag)
	isCorrect := false
	if flag >= 0 && flag <= 3 {
		clinet.flag = flag
		isCorrect = true
	} else {
		fmt.Println(">>>请输入合法范围内的数字<<<<")

	}
	return isCorrect
}

func (clinet *Client) Run() {

	for clinet.flag != 0 {
		for clinet.menu() != true {

		}
		//根据不同的模式处理不同的业务

		switch clinet.flag {
		case 1:
			//私聊
			//fmt.Println(">>>公聊模式<<<<")
			clinet.PublicChat()
			break
		case 2:
			//fmt.Println(">>>私聊模式<<<<")
			clinet.PrivateChat()
			break
		case 3:
			//fmt.Println(">>>修改用户名模式<<<<")
			clinet.UpdateName()
			break

		}
	}
}

//client.exe -ip 127.0.0.1 -port 8888 命令行解析
var serverIp string
var serverPort int

func init() {
	flag.StringVar(&serverIp, "ip", "127.0.0.1", "设置服务器IP地址（默认是127.0.0.1）")
	flag.IntVar(&serverPort, "port", 8888, "设置服务器端口，默认是8888")
}

func main() {
	flag.Parse()
	client := NewClient(serverIp, serverPort)
	if client == nil {
		fmt.Println(">>>>>>连接服务器失败...")
		return
	}
	fmt.Println(">>>>>>连接服务器成功")

	//单独开始一个goroutine去处理server的回执消息
	go client.DealRespone()

	//启动客户端业务
	client.Run()

}
